package cn.yunyichina.provider.base.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fy.util.AppException;
import com.fy.util.db.DaoConfig;
import com.fy.util.db.JdbcDao;

/**
 * 智慧医院数据库
 * @author adriftor
 *
 */
public class ZhyySourceDao extends JdbcDao implements AutoCloseable {
	
	private static final Logger logger = LoggerFactory.getLogger(ZhyySourceDao.class);

	static ThreadLocal<Connection> tlCon = new ThreadLocal<Connection>();

	public ZhyySourceDao() {
		this.setDatabaseType(DaoConfig.DATABASE_TYPE_MYSQL);
		this.setUserControlConnection(true);
	}
	
	static ResourceBundle rb;
	static {
		rb = ResourceBundle.getBundle("conf.oldjdbc");
	}
	
	
	@Override
	public Connection getConnection() {
		Connection innerCon = tlCon.get();
		try {
			
			if (innerCon != null &&( ! innerCon.isClosed())) {
				return innerCon;
			}
			
			String strDriver = rb.getString("driverClassName");
			Class.forName(strDriver);

			//测试
			innerCon = DriverManager.getConnection(rb.getString("url"), rb.getString("username"), rb.getString("password")); 
			
			tlCon.set(innerCon); 
			

		} catch (Exception se) {
			throw new AppException("数据库连接错误", se);
		}

		return innerCon;

	
	}
	
	@Override
	public void releaseCon() {

		if (!this.isUserControlConnection()) {
			return;
		}

		int iCloseConnection = this.getCountCloseConnection();
		if (iCloseConnection > 0) {
			return;
		}
		Connection innerCon = this.getConnection();

		if (innerCon != null) {
			try {
				
				innerCon.close();
				tlCon.remove();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		innerCon = null;

	}

	@Override
	public void close() throws Exception {
		releaseCon();
		
	}
	
	public static void main(String[] argv) {
		System.out.println(rb.getString("url"));
	}

}
